//
//  ReleaseAfterSaleViewController.swift
//  OnceNectar
//
//  Created by apple on 2018/3/7.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import AVFoundation
import AssetsLibrary
import Photos
import PhotosUI
import MobileCoreServices
import SwiftyJSON
import IQKeyboardManagerSwift
import Networking
import Alamofire
import PKHUD
import TCPickerView

class ReleaseAfterSaleViewController: BaseViewController, BottomShadow,UITextViewDelegate,UploadImgCollectionViewCellDelegate,ImageCollectionViewCellDelegate,UICollectionViewDelegate, UICollectionViewDataSource,UIImagePickerControllerDelegate {
    
    @IBOutlet var bgView: UIView!
    @IBOutlet weak var resonBtn: UIButton!
    
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var countNum: UILabel!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    var model:myOrderModel?
    var imgArr = [UIImage]()
    var imgIds = [String]()
    var jointId:String = ""
    var itemWidth: CGFloat?
    var pgiId:String?
    var type:String = "0"
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }
    override func setNavigation() {
        let button = UIButton(type: .custom)
        button.setTitle("提交", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        button.addTarget(self, action: #selector(submit), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }
    func initUI() {
        titleLabel(text: "售后服务", nil)
        
        self.textView.delegate = self
        
        collectionView.collectionViewLayout = getFlowLayout()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib.init(nibName: "\(UploadImgCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(UploadImgCollectionViewCell.self)")
        collectionView.register(UINib.init(nibName: "\(ImageCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(ImageCollectionViewCell.self)")
        collectionView.reloadData()

        setShadow(view: bgView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
    }
    @IBAction func btnClick(_ sender: Any) {
        let picker: TCPickerView = TCPickerView()
        picker.title = "选择原因"
        var cars :[String] = []
        cars.append("退货")
        cars.append("换货")
        cars.append("其他")
        let values = cars.map { TCPickerView.Value(title: $0) }
        picker.values = values
        picker.selection = .single
        picker.completion = { (selectedIndexes) in
            for i in selectedIndexes {
                self.type = String.init(i)
                self.resonBtn.setTitle(values[i].title, for: UIControlState.normal)
            }
        }
        picker.show()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    func getFlowLayout() -> UICollectionViewFlowLayout {
        var flowLayout = UICollectionViewFlowLayout()
        
        flowLayout = UICollectionViewFlowLayout()
        let itemSize = (ScreenWidth - 100) / 3
        self.itemWidth = itemSize
        flowLayout.itemSize = CGSize(width: itemSize, height: itemSize)
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = 20;
        flowLayout.minimumLineSpacing = 10;
        flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
        return flowLayout
    }
    
    public func textViewDidChange(_ textView: UITextView) {
        if textView.text.characters.count > 0 {
            
            //获得已输出字数与正输入字母数
            let selectRange = textView.markedTextRange
            
            //获取高亮部分 － 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            
            let textContent = textView.text
            let textNum = textContent?.characters.count
            
            //截取200个字
            if textNum! > 300 {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: 300)
                let str = textContent?.substring(to: index!)
                textView.text = str
            }
        }
        self.countNum.text =  "\(textView.text.characters.count)/\(300)"
    }
    
    func addImage() {
        if imgArr.count == 5 {
            self.showToast(msg: "最多只能添加5张图片")
            return
        }
        let alertController:UIAlertController = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let takePhotoAction:UIAlertAction = UIAlertAction.init(title: "拍照", style: UIAlertActionStyle.default) { (action) in
            self.takePhoto()
        }
        
        let choosePhotoAction:UIAlertAction = UIAlertAction.init(title: "相册", style: UIAlertActionStyle.default) { (action) in
            self.selectPhoto()
        }
        
        let cancelAction:UIAlertAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel) { (action) in
        }
        alertController.addAction(takePhotoAction)
        alertController.addAction(choosePhotoAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true) {
            
        }
    }
    
    func delIamge(cell: ImageCollectionViewCell) {
        let indexPath = self.collectionView.indexPath(for: cell)
        self.imgArr.remove(at: (indexPath?.item)!)
        let imgId:String = self.imgIds[(indexPath?.item)!]
        delImagereq(id: imgId)
        self.imgIds.remove(at: (indexPath?.item)!)
        if imgArr.count == 2 {
            self.collectionViewHeight.constant -= self.itemWidth! + 20
        }
        self.collectionView.deleteItems(at: [indexPath!])
    }
    
    func delImagereq(id:String) {
        let requesturl = appendUrl(suffix: deleteFielUrl + "/" + id)
        Alamofire.request(requesturl, method: .post,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            
        }
    }
    
    func addImageCallBak(image:UIImage,jointId:String,imgId:String) -> Void {
        if self.jointId == "" {
            self.jointId = jointId
        }
        self.imgIds.insert(imgId, at: 0)
    }
    
    // MARK: - CollectionViewDatasource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.imgArr.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let count = self.imgArr.count + 1
        if indexPath.item == count - 1{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(UploadImgCollectionViewCell.self)", for: indexPath) as! UploadImgCollectionViewCell
            cell.delegate = self
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(ImageCollectionViewCell.self)", for: indexPath) as! ImageCollectionViewCell
            cell.delegate = self
            cell.img.image = self.imgArr[indexPath.item]
            return cell
        }
    }
    
    func takePhoto() {
        let imagePickerController:UIImagePickerController = UIImagePickerController.init()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
        imagePickerController.allowsEditing = false
        imagePickerController.showsCameraControls = true
        imagePickerController.videoQuality = UIImagePickerControllerQualityType.typeIFrame1280x720
        imagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.rear
        imagePickerController.mediaTypes = [kUTTypeImage as String]
        self.present(imagePickerController, animated: true, completion: nil)
    }
    
    func selectPhoto() {
        let imagePickerController:UIImagePickerController = UIImagePickerController.init()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePickerController.allowsEditing = false
        imagePickerController.mediaTypes = [kUTTypeImage as String]
        self.present(imagePickerController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType:String = info[UIImagePickerControllerMediaType] as! String
        if mediaType == kUTTypeImage as String {
            let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            self.imgArr.insert(image, at: 0)
            if imgArr.count == 3 {
                self.collectionViewHeight.constant += self.itemWidth! + 20
            }
            let indexPath = IndexPath.init(item: 0, section: 0)
            self.collectionView.insertItems(at: [indexPath])
            picker.dismiss(animated: true) {
                self.uploadImage(img: image)
            }
        }
    }
    
    func uploadImage(img:UIImage) {
        let upload:MMFileUploadUtil = MMFileUploadUtil.init()
        upload.uploadFile(with: UIImageJPEGRepresentation(img, 0), fs: "9", jointId: self.jointId) { (response, error) in
            if (error != nil) {
                self.showToast(msg:"上传失败")
                return
            }
            let sudi: NSDictionary? = response as? NSDictionary
            let json = JSON(sudi)
            let joindata = json["data"].dictionary
            let joint = joindata!["jointId"]
            let imgId:String = (joindata!["id"]?.number?.stringValue)!
            self.addImageCallBak(image: img, jointId: (joint?.string)!, imgId:imgId)
        }
    }
    
    @objc func submit() -> Void {
        if textView.text == "" {
            self.showToast(msg: "请填写原因")
            return
        }
        if self.jointId == "" {
            self.showToast(msg: "请上传至少一张图片")
            return
        }
        if !(self.isValidPhone(phone: phoneField.text! as NSString)) {
            self.showToast(msg:"请填写正确的手机号码")
            return
        }
        
        self.submitReq(params: ["piId":(self.model?.id!)!,"pgiId":self.pgiId!,"asType":self.type,"asReason":textView.text,"jointId":self.jointId,"mp":phoneField.text!])
    }
    
    func submitReq(params:[String:String]) -> Void {
        let requesturl = appendUrl(suffix: applyAfterService)
        Alamofire.request(requesturl, method: .post,
                          parameters: params,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        CustomShowAlertView().show(title: "提交成功！小蜜会马上联系您，请保持电话通畅", tapClosure: {
                                            self.navigationController?.popViewController(animated: true)
                                        })
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
}
